package org.jeefb.web.sys.controller;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.jeefb.common.ServiceResult;
import org.jeefb.modules.sys.contants.SystemCachedContants;
import org.jeefb.modules.sys.service.CachedService;
import org.jeefb.modules.sys.service.SystemService;
import org.jeefb.modules.sys.service.UserService;
import org.jeefb.modules.sys.vo.UserBaseVO;
import org.jeefb.modules.sys.vo.UserLoginVO;
import org.jeefb.modules.sys.vo.UserVO;
import org.jeefb.web.utils.AjaxJson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;

@Controller
public class LoginController extends BaseController {
	private static final Logger logger = Logger.getLogger(LoginController.class);
	@Autowired
	private UserService userService;
	@Autowired
	private CachedService cachedService;
	@Autowired
	private SystemService systemService;
    /**
     * 
     * @Description: 用户登录
     * @param request
     * @return    
     * @return String
     */
	@RequestMapping("login")
	public String index(HttpServletRequest request) {
		ServiceResult<String> result = cachedService.getCachedObjectByKey(SystemCachedContants.ADMIN_USER_SESSION+request.getSession().getId());
		if(result.getSuccess() && result.getResult() !=null){
			UserBaseVO userBaseVO = JSON.parseObject(result.getResult(),UserBaseVO.class);
			if(userBaseVO != null){
				ServiceResult<UserVO> userResult = systemService.getUserVO(userBaseVO.getId(), request.getSession().getId());
				if (userResult.getSuccess() && userResult.getResult() != null) {
					request.setAttribute("user", userResult.getResult().getUserBaseVO());
					request.setAttribute("functionList", userResult.getResult().getFunctions());
					return theme + "/main/index";
				}
			}
		}
		return theme + "/login/login";
	}

	@RequestMapping("checkuser")
	@ResponseBody
	public AjaxJson checkuser(HttpServletRequest request, UserLoginVO user) {
		logger.debug("请求参数：" + JSON.toJSONString(user));
		AjaxJson j = new AjaxJson();
		if (user.getPassword() != null && user.getUserName() != null && user.getVerfiyCode() != null) {
			ServiceResult<UserBaseVO> result = userService.login(user, request.getSession().getId());
			if (result.getSuccess() && result.getResult() != null) {
				j.setObj(result.getResult().getId());
			}else if(result.getSuccess() && result.getResult() == null){
				j.setMsg(getLanguageContext(result.getCode()));
			 } else {
				 j.setMsg(getLanguageContext("system.error")); 
			 }
		} else {
			 j.setMsg(getLanguageContext("parameters.error")); 
		}
		return j;

	}

	@RequestMapping("logout")
	public String logout(HttpServletRequest request) {
		return "redirect:/" + theme + "/login";
	}

}
